/*
 LegislatorViewController.m
 LegislatorLookup
 
 This is the controller for the Legislator List. This page displays all the
 details about a candidate
 
 Copyright (c) 2009 Nabil Ahmad
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 
 1. Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
 
 2. Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the 
 documentation and/or other materials provided with the distribution. 
 
 3. The name of the author may not be used to endorse or promote products
 derived from this software without specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */	

#import "LegislatorViewController.h"
#import "TwitterFeedViewController.h"
#import "ContributorViewController.h"
#import "IndustryViewController.h"
#import "PFDViewController.h"
#import "WebServiceController.h"
#import "WebViewController.h"

#define LABEL_TAG 1
#define VALUE_TAG 2
#define FIRST_CELL_IDENTIFIER @"FIRST_CELL"
#define SECOND_CELL_IDENTIFIER @"SECOND_CELL"

// list sections
#define POS_SECTION 0
#define CON_SECTION 1
#define WEB_SECTION 2
#define FINANCE_SECTION 3
#define FINANCE_SUB_PFD 0
#define FINANCE_SUB_CONTRIB 1
#define FINANCE_SUB_INDUSTRY 2

@implementation LegislatorViewController

// Custom init passing Legislator
- (id) initWithLegislator:(Legislator *)person 
{
	[super initWithStyle:UITableViewStyleGrouped];
	legislator = person;
	
	return self;
}

- (void)loadView 
{
	[super loadView];
	self.title = @"Info";
	isDataLoaded = NO;
	
	// load all the plists containing labels/keys for sections
	NSString *postListPath = [[NSBundle mainBundle] pathForResource:@"LegislatorViewPositionSection" ofType:@"plist"];
	NSString *contListPath = [[NSBundle mainBundle] pathForResource:@"LegislatorViewContactSection" ofType:@"plist"];
	NSString *webListPath = [[NSBundle mainBundle] pathForResource:@"LegislatorViewWebSection" ofType:@"plist"];
	NSString *financeListPath = [[NSBundle mainBundle] pathForResource:@"LegislatorViewFinanceSection" ofType:@"plist"];
	NSString *labelsListPath = [[NSBundle mainBundle] pathForResource:@"LegislatorViewLabels" ofType:@"plist"];

	positionSection = [[NSArray arrayWithContentsOfFile:postListPath] retain];
	contactSection = [[NSArray arrayWithContentsOfFile:contListPath] retain];
	webSection = [[NSArray arrayWithContentsOfFile:webListPath] retain];
	financeSection = [[NSArray arrayWithContentsOfFile:financeListPath] retain];
	labels = [[NSDictionary dictionaryWithContentsOfFile:labelsListPath] retain];
	
	sections = [[NSMutableArray alloc] init];
	[sections addObject:positionSection];
	[sections addObject:contactSection];
	[sections addObject:webSection];
	[sections addObject:financeSection];
}

// load data and rerender view after view is loaded
- (void)viewDidAppear:(BOOL)animated
{
	//Load contribution data
	[legislator setContributionData:[WebServiceController getCandidateContributionSummary:[legislator.legislatorData objectForKey:@"crp_id"]]];
	isDataLoaded = YES;
	
	// Create Table header & footer
	[self createTableHeaderAndFooter];
	
	[self.tableView reloadData];
}

// code to create header and footer
- (void) createTableHeaderAndFooter 
{
	// table header
	CGRect titleRect = CGRectMake(0, 0, 320, 40);
    UILabel *tableTitle = [[UILabel alloc] initWithFrame:titleRect];
    tableTitle.textColor = [UIColor blackColor];
    tableTitle.backgroundColor = [UIColor clearColor];
    tableTitle.opaque = YES;
    tableTitle.font = [UIFont boldSystemFontOfSize:18];
    tableTitle.text = legislator.headerName;
	tableTitle.textAlignment = UITextAlignmentCenter;
    self.tableView.tableHeaderView = tableTitle;
    [tableTitle release];
	
	// table footer
	CGRect footerRect = CGRectMake(0, 0, 320, 30);
    UILabel *footerText = [[UILabel alloc] initWithFrame:footerRect];
    footerText.textColor = [UIColor grayColor];
    footerText.backgroundColor = [UIColor clearColor];
    footerText.opaque = YES;
	footerText.numberOfLines = 0;
    footerText.font = [UIFont systemFontOfSize:12];
    footerText.text = @"Content provided by www.sunlightlabs.com and Center for Responsive Politics";
	footerText.textAlignment = UITextAlignmentCenter;
    self.tableView.tableFooterView = footerText;
    [footerText release];	
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

// Return count of sections array
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	int count = 1;
	if (isDataLoaded)
		count = [sections count] ;
	
	return count;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	int count = 0;
	if (isDataLoaded)
		count =[[sections objectAtIndex:section] count];
	
	return count;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

	// Render everything BUT finance section with two column cell
	if (FINANCE_SECTION != indexPath.section)
	{
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FIRST_CELL_IDENTIFIER];
		UILabel *label, *value;
		
		if (cell == nil) 
		{	
			CGRect frame = CGRectMake(0, 0, 300, 44);	
			cell = [[[UITableViewCell alloc] initWithFrame:frame reuseIdentifier:FIRST_CELL_IDENTIFIER] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			
			label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 12.0, 90.0, 25.0)] autorelease];
			label.tag = LABEL_TAG;
			label.font = [UIFont boldSystemFontOfSize:12.0];
			label.textAlignment = UITextAlignmentRight;
			label.textColor = [UIColor grayColor];
			label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
			[cell.contentView addSubview:label];
			
			value = [[[UILabel alloc] initWithFrame:CGRectMake(95.0, 12.0, 205.0, 25.0)] autorelease];
			value.tag = VALUE_TAG;
			value.font = [UIFont boldSystemFontOfSize:12.0];
			value.textColor = [UIColor blackColor];
			value.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
			[cell.contentView addSubview:value];
		} else {
			
			label = (UILabel *)[cell.contentView viewWithTag:LABEL_TAG];	
			value = (UILabel *)[cell.contentView viewWithTag:VALUE_TAG];
		}
		
		label.text = [labels objectForKey:[[sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
		value.text = [legislator getField:[[sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
		
		return cell;
	}
	// Render Finance Section
	else
	{
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SECOND_CELL_IDENTIFIER];
		
		if (cell == nil) {
			cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SECOND_CELL_IDENTIFIER] autorelease];
		}
		cell.textAlignment = UITextAlignmentLeft;
		cell.font = [UIFont boldSystemFontOfSize:12.0];
		cell.text = [[sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
		
		return cell;
	}
}

// Render appropirate accessory type
- (UITableViewCellAccessoryType)tableView:(UITableView *)table accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
	NSString *key = [[sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
	NSString *value =  [legislator.legislatorData objectForKey:[[sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
	
	if (((indexPath.section == WEB_SECTION) 
		 || [key isEqualToString:@"phone"] 
		 || [key isEqualToString:@"email"] || [key isEqualToString:@"congress_office"]
		 || [key isEqualToString:@"twitter_id"]) && (value.length > 0))
		return UITableViewCellAccessoryDisclosureIndicator;
	else if (indexPath.section == FINANCE_SECTION)
		return UITableViewCellAccessoryDisclosureIndicator;
	else 
		return UITableViewCellAccessoryNone;
}

// Determine what action to take for each row
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
	NSString *key = [[sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
	NSString *value =  [legislator.legislatorData objectForKey:[[sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];

	if ([value length] > 0) 
	{
		// open links in web view
		if (indexPath.section == WEB_SECTION) 
		{
			WebViewController *webViewController = [[WebViewController alloc] initWithNibAndUrl:@"WebView" bundle:nil url:[NSURL URLWithString:value]];
			[self.navigationController pushViewController:webViewController	animated:YES];
			[webViewController release];
		}	
		// allow iphone to handle special links
		else if ([key isEqualToString:@"phone"]) 
		{
			value = [NSString stringWithFormat:@"tel:%@",value];
			[[UIApplication sharedApplication] openURL:[NSURL URLWithString:value]];
		}
		else if ([key isEqualToString:@"email"])
		{
			value = [NSString stringWithFormat:@"mailto:%@",value];
			[[UIApplication sharedApplication] openURL:[NSURL URLWithString:value]];
		}	
		else if ([key isEqualToString:@"congress_office"])
		{
			value = [value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
			value = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@",value];
			
			WebViewController *webViewController = [[WebViewController alloc] initWithNibAndUrl:@"WebView" bundle:nil url:[NSURL URLWithString:value]];
			[self.navigationController pushViewController:webViewController	animated:YES];
			[webViewController release];
			
		}
		// open twitter links in internal twitter viewer
		else if ([key isEqualToString:@"twitter_id"])
		{
			TwitterFeedViewController *twitterFeedViewController = [[TwitterFeedViewController alloc] initWithTwitterId:value];
			
			[self.navigationController pushViewController:twitterFeedViewController animated:YES];
			[twitterFeedViewController release];
		}
	}
	// Open Appropriate Views
	else if (FINANCE_SECTION == indexPath.section && FINANCE_SUB_PFD == indexPath.row)
	{
		NSString *candId =  [legislator.legislatorData objectForKey:@"crp_id"];
		PFDViewController *pfdViewController = [[PFDViewController alloc] initWithCandidateId:candId];
		[self.navigationController pushViewController:pfdViewController	animated:YES];
		[pfdViewController release];
	}
	else if (FINANCE_SECTION == indexPath.section && FINANCE_SUB_CONTRIB == indexPath.row)
	{
		NSString *candId =  [legislator.legislatorData objectForKey:@"crp_id"];
		ContributorViewController *contributorViewController = [[ContributorViewController alloc] initWithCandidateId:candId];
		[self.navigationController pushViewController:contributorViewController	animated:YES];
		[contributorViewController release];
	}
	else if (FINANCE_SECTION == indexPath.section && FINANCE_SUB_INDUSTRY == indexPath.row)
	{
		NSString *candId =  [legislator.legislatorData objectForKey:@"crp_id"];
		IndustryViewController *industryViewController = [[IndustryViewController alloc] initWithCandidateId:candId];
		[self.navigationController pushViewController:industryViewController	animated:YES];
		[industryViewController release];
	}
}

// Return labels
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	NSString *title = nil;
	
	if (CON_SECTION == section)
		title = @"Contact Information";
	else if (WEB_SECTION == section)
		title = @"Web Sites";
	else if (FINANCE_SECTION == section)
		title = @"Financial Information";
	
	return  title;
}

- (void)dealloc {
    [super dealloc];
}


@end

